package struts.util;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

public class StrutsConfig {
	
	public static Map<String, XmlBean> parseXml(String xmlPath){
		Map<String, XmlBean> map = new HashMap<String, XmlBean>();
		try {
			SAXBuilder builder = new SAXBuilder();
			Document document = builder.build(new File(xmlPath));
			Element root = document.getRootElement();
			Element formroot = root.getChild("formbeans");
			
			
			Element actionroot = root.getChild("action-mapping");
			List<Element> actions = actionroot.getChildren();
			List<Element> forms = formroot.getChildren();
			
			for(Element action : actions){
				XmlBean xmlBean = new XmlBean();
				String name = action.getAttributeValue("name");
				for(Element form : forms){
					if(name.equals(form.getAttributeValue("name"))){
						xmlBean.setFormClass(form.getAttributeValue("class"));
						break;
					}
				}
				xmlBean.setBeanName(action.getAttributeValue("name"));
				xmlBean.setPath(action.getAttributeValue("path"));
				xmlBean.setActionType(action.getAttributeValue("type"));
				List<Element> forwards = action.getChildren();
				Map<String, String> forwardMap = new HashMap<String, String>();
				for(Element forward : forwards){
					String forwardName = forward.getAttributeValue("name");
					String forwardValue = forward.getAttributeValue("value");
					forwardMap.put(forwardName, forwardValue);
				}
				xmlBean.setForwardMap(forwardMap);
				map.put(xmlBean.getPath(), xmlBean);
			}
			
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		return map;
	}
	
	

}
